<template>
  <Head :title="`售后申请详情 #${request.id}`" />
  <ShopLayout>
    <div class="bg-gray-100 min-h-screen">
      <div class="max-w-7xl mx-auto px-8 sm:px-16 lg:px-24 py-20">
        <!-- 页面标题 -->
        <div class="mb-8">
          <div class="flex items-center justify-between">
            <div class="flex items-center space-x-4">
              <Link 
                :href="route('after-sales.index')"
                class="text-gray-600 hover:text-gray-900"
              >
                <svg class="h-6 w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
                </svg>
              </Link>
              <div>
                <h1 class="text-3xl font-light text-gray-900">
                  售后申请详情 #{{ request.id }}
                </h1>
                <p class="mt-2 text-gray-600">查看售后申请的处理进度</p>
              </div>
            </div>
            
            <div class="flex items-center space-x-3">
              <span 
                :class="getStatusBadgeClass(request.status)"
                class="inline-flex items-center px-4 py-2 rounded-2xl text-sm font-medium"
              >
                {{ getStatusText(request.status) }}
              </span>
              <span 
                :class="getTypeBadgeClass(request.type)"
                class="inline-flex items-center px-4 py-2 rounded-2xl text-sm font-medium"
              >
                {{ getTypeText(request.type) }}
              </span>
            </div>
          </div>
        </div>

        <div class="space-y-6">
          <!-- 申请基本信息 -->
          <div class="bg-white rounded-2xl p-8 shadow-sm">
            <h2 class="text-2xl font-light text-gray-900 mb-6">申请信息</h2>
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">申请类型</label>
                <p class="text-lg text-gray-900">{{ getTypeText(request.type) }}</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">申请原因</label>
                <p class="text-lg text-gray-900">{{ request.reason }}</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">申请金额</label>
                <p class="text-lg text-gray-900">¥{{ request.requested_amount }}</p>
              </div>
              <div v-if="request.approved_amount">
                <label class="block text-sm font-medium text-gray-700 mb-2">批准金额</label>
                <p class="text-lg text-gray-900">¥{{ request.approved_amount }}</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">申请时间</label>
                <p class="text-lg text-gray-900">{{ formatDate(request.created_at) }}</p>
              </div>
              <div v-if="request.submitted_at">
                <label class="block text-sm font-medium text-gray-700 mb-2">提交时间</label>
                <p class="text-lg text-gray-900">{{ formatDate(request.submitted_at) }}</p>
              </div>
            </div>
            
            <div v-if="request.description" class="mt-6">
              <label class="block text-sm font-medium text-gray-700 mb-2">详细说明</label>
              <div class="bg-gray-50 rounded-2xl p-4">
                <p class="text-gray-900 whitespace-pre-wrap">{{ request.description }}</p>
              </div>
            </div>
          </div>

          <!-- 订单信息 -->
          <div class="bg-white rounded-2xl p-8 shadow-sm">
            <h2 class="text-2xl font-light text-gray-900 mb-6">关联订单</h2>
            
            <div class="flex items-center justify-between">
              <div class="space-y-2">
                <p class="text-lg font-medium text-gray-900">订单号：{{ request.order.order_number }}</p>
                <p class="text-lg text-gray-600">订单状态：{{ getOrderStatusText(request.order.status) }}</p>
                <p class="text-lg text-gray-600">订单金额：¥{{ request.order.total_amount }}</p>
              </div>
              <Link 
                :href="route('order.show', request.order.order_number)"
                class="px-6 py-3 border border-gray-300 rounded-2xl text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900"
              >
                查看订单详情
              </Link>
            </div>
          </div>

          <!-- 售后商品 -->
          <div class="bg-white rounded-2xl p-8 shadow-sm">
            <h2 class="text-2xl font-light text-gray-900 mb-6">售后商品</h2>
            
            <div class="space-y-6">
              <div 
                v-for="item in request.items" 
                :key="item.id"
                class="border border-gray-200 rounded-2xl p-6"
              >
                <div class="flex items-start space-x-4">
                  <img 
                    :src="item.order_item.product.image || '/images/product-placeholder.svg'"
                    :alt="item.order_item.product.name"
                    class="h-20 w-20 rounded-2xl object-cover"
                  >
                  
                  <div class="flex-1">
                    <h3 class="text-lg font-medium text-gray-900">{{ item.order_item.product.name }}</h3>
                    <p v-if="item.order_item.variant" class="text-sm text-gray-500 mt-1">
                      规格：{{ item.order_item.variant.name }}
                    </p>
                    <div class="mt-4">
                      <div>
                        <span class="font-medium text-gray-700">售后数量：</span>
                        <span class="text-gray-900">{{ item.quantity }}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 凭证图片 -->
          <div v-if="request.images && request.images.length > 0" class="bg-white rounded-2xl p-8 shadow-sm">
            <h2 class="text-2xl font-light text-gray-900 mb-6">凭证图片</h2>
            
            <div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-4">
              <div 
                v-for="(image, index) in request.images" 
                :key="index"
                class="relative group cursor-pointer"
                @click="openImageModal(image)"
              >
                <img 
                  :src="getImageUrl(image)" 
                  :alt="`凭证图片 ${index + 1}`"
                  class="h-24 w-full object-cover rounded-2xl border border-gray-300 hover:border-gray-900 transition-colors"
                >
                <div class="absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-20 transition-all rounded-2xl flex items-center justify-center">
                  <svg class="h-6 w-6 text-white opacity-0 group-hover:opacity-100 transition-opacity" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0zM10 7v3m0 0v3m0-3h3m-3 0H7" />
                  </svg>
                </div>
              </div>
            </div>
          </div>

          <!-- 换货流程进度 -->
          <div v-if="request.type === 'exchange' && request.status === 'processing'" class="bg-white rounded-2xl p-8 shadow-sm">
            <div class="flex items-center mb-8">
              <div class="flex-shrink-0">
                <svg class="h-8 w-8 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v10a2 2 0 002 2h8a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
                </svg>
              </div>
              <div class="ml-4">
                <h2 class="text-2xl font-light text-gray-900">换货流程</h2>
                <p class="text-gray-600">您的换货申请处理进度</p>
              </div>
            </div>
            
            <div class="space-y-6">
              <!-- 流程步骤 -->
              <div class="space-y-4">
                <div class="flex items-center">
                  <div :class="getExchangeStepClass('return_shipped')" class="w-8 h-8 rounded-full flex items-center justify-center mr-4">
                    <svg v-if="isExchangeStepCompleted('return_shipped')" class="w-5 h-5 text-white" fill="currentColor" viewBox="0 0 20 20">
                      <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
                    </svg>
                    <span v-else class="text-sm font-bold">{{ getExchangeStepNumber('return_shipped') }}</span>
                  </div>
                  <div class="flex-1">
                    <h3 :class="getExchangeStepTextClass('return_shipped')" class="text-lg font-medium">用户已寄回</h3>
                    <p class="text-sm text-gray-500">您已寄回原商品，等待商家确认收货</p>
                  </div>
                </div>
                
                <div class="flex items-center">
                  <div :class="getExchangeStepClass('return_received')" class="w-8 h-8 rounded-full flex items-center justify-center mr-4">
                    <svg v-if="isExchangeStepCompleted('return_received')" class="w-5 h-5 text-white" fill="currentColor" viewBox="0 0 20 20">
                      <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
                    </svg>
                    <span v-else class="text-sm font-bold">{{ getExchangeStepNumber('return_received') }}</span>
                  </div>
                  <div class="flex-1">
                    <h3 :class="getExchangeStepTextClass('return_received')" class="text-lg font-medium">商家已收货</h3>
                    <p class="text-sm text-gray-500">商家已确认收到您寄回的商品</p>
                  </div>
                </div>
                
                <div class="flex items-center">
                  <div :class="getExchangeStepClass('new_sent')" class="w-8 h-8 rounded-full flex items-center justify-center mr-4">
                    <svg v-if="isExchangeStepCompleted('new_sent')" class="w-5 h-5 text-white" fill="currentColor" viewBox="0 0 20 20">
                      <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
                    </svg>
                    <span v-else class="text-sm font-bold">{{ getExchangeStepNumber('new_sent') }}</span>
                  </div>
                  <div class="flex-1">
                    <h3 :class="getExchangeStepTextClass('new_sent')" class="text-lg font-medium">新商品已寄出</h3>
                    <p class="text-sm text-gray-500">商家已寄出新的商品，请注意查收</p>
                  </div>
                </div>
                
                <div class="flex items-center">
                  <div :class="getExchangeStepClass('new_delivered')" class="w-8 h-8 rounded-full flex items-center justify-center mr-4">
                    <svg v-if="isExchangeStepCompleted('new_delivered')" class="w-5 h-5 text-white" fill="currentColor" viewBox="0 0 20 20">
                      <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
                    </svg>
                    <span v-else class="text-sm font-bold">{{ getExchangeStepNumber('new_delivered') }}</span>
                  </div>
                  <div class="flex-1">
                    <h3 :class="getExchangeStepTextClass('new_delivered')" class="text-lg font-medium">新商品已送达</h3>
                    <p class="text-sm text-gray-500">新商品已送达，换货流程即将完成</p>
                  </div>
                  <div class="ml-auto flex items-center space-x-3">
                    <!-- 超时提醒 -->
                    <div v-if="isNearTimeout" class="text-orange-600 text-sm">
                      <svg class="w-4 h-4 inline mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z" />
                      </svg>
                      {{ getTimeoutMessage() }}
                    </div>
                    <button 
                      v-if="canConfirmNewDelivered"
                      @click="confirmNewDelivered"
                      :disabled="isProcessing"
                      class="px-4 py-2 bg-gray-900 text-white text-sm rounded-xl hover:bg-gray-800 disabled:opacity-50"
                    >
                      确认送达
                    </button>
                  </div>
                </div>
              </div>
              
              <!-- 当前状态提示 -->
              <div v-if="getCurrentStepDescription()" class="mt-6 p-4 bg-blue-50 rounded-2xl border border-blue-200">
                <div class="flex items-start">
                  <svg class="h-5 w-5 text-blue-600 mt-0.5 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                  <div>
                    <h4 class="text-sm font-medium text-blue-900">当前状态</h4>
                    <p class="text-sm text-blue-700 mt-1">{{ getCurrentStepDescription() }}</p>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 处理记录 -->
          <div v-if="request.approvals && request.approvals.length > 0" class="bg-white rounded-2xl p-8 shadow-sm">
            <div class="flex items-center mb-8">
              <div class="flex-shrink-0">
                <svg class="h-8 w-8 text-gray-900" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                </svg>
              </div>
              <div class="ml-4">
                <h2 class="text-2xl font-light text-gray-900">处理记录</h2>
                <p class="text-gray-600">售后申请的处理历史</p>
              </div>
            </div>
            
            <div class="flow-root">
              <ul class="-mb-8">
                <li 
                  v-for="(approval, index) in request.approvals" 
                  :key="approval.id"
                  class="relative pb-8"
                >
                  <div v-if="index !== request.approvals.length - 1" class="absolute top-4 left-4 -ml-px h-full w-0.5 bg-gray-200" aria-hidden="true"></div>
                  <div class="relative flex space-x-3">
                    <div>
                      <span class="h-8 w-8 rounded-full bg-gray-900 flex items-center justify-center ring-8 ring-white">
                        <svg class="h-4 w-4 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
                        </svg>
                      </span>
                    </div>
                    <div class="min-w-0 flex-1 pt-1.5 flex justify-between space-x-4">
                      <div>
                        <p class="text-lg font-medium text-gray-900">{{ getApprovalActionText(approval.action) }}</p>
                        <p v-if="approval.comment" class="mt-2 text-gray-600 bg-gray-50 rounded-2xl p-4">{{ approval.comment }}</p>
                      </div>
                      <div class="text-right text-sm whitespace-nowrap text-gray-500">
                        <p class="font-medium text-gray-900">{{ approval.admin?.name || '系统' }}</p>
                        <p>{{ formatDate(approval.created_at) }}</p>
                      </div>
                    </div>
                  </div>
                </li>
              </ul>
            </div>
          </div>

          <!-- 物流信息填写表单（审核通过且需要物流信息时） -->
          <div v-if="shouldShowLogisticsForm" class="bg-white rounded-2xl p-8 shadow-sm">
            <div class="flex items-center mb-8">
              <div class="flex-shrink-0">
                <svg class="h-8 w-8 text-gray-900" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
                </svg>
              </div>
              <div class="ml-4">
                <h2 class="text-2xl font-light text-gray-900">填写物流信息</h2>
                <p class="text-gray-600">请填写寄回商品的物流信息</p>
              </div>
            </div>
            
            <form @submit.prevent="submitLogisticsForm" class="space-y-6">
              <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-2">物流公司 *</label>
                  <select 
                    v-model="logisticsForm.company"
                    class="w-full px-4 py-3 border border-gray-300 rounded-2xl shadow-sm focus:ring-2 focus:ring-gray-900 focus:border-gray-900"
                  >
                    <option value="">请选择物流公司</option>
                    <option 
                      v-for="company in logisticsCompanies" 
                      :key="company.id" 
                      :value="company.name"
                    >
                      {{ company.name }} ({{ company.code }})
                    </option>
                  </select>
                  <div v-if="logisticsErrors.company" class="mt-2 text-sm text-red-600">{{ logisticsErrors.company }}</div>
                </div>
                
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-2">物流单号 *</label>
                  <input 
                    v-model="logisticsForm.tracking_number"
                    type="text"
                    class="w-full px-4 py-3 border border-gray-300 rounded-2xl shadow-sm focus:ring-2 focus:ring-gray-900 focus:border-gray-900"
                    placeholder="请输入物流单号"
                  >
                  <div v-if="logisticsErrors.tracking_number" class="mt-2 text-sm text-red-600">{{ logisticsErrors.tracking_number }}</div>
                </div>
                
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-2">寄件人姓名</label>
                  <input 
                    v-model="logisticsForm.sender_name"
                    type="text"
                    class="w-full px-4 py-3 border border-gray-300 rounded-2xl shadow-sm focus:ring-2 focus:ring-gray-900 focus:border-gray-900"
                    placeholder="您的姓名"
                  >
                </div>
                
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-2">寄件人电话</label>
                  <input 
                    v-model="logisticsForm.sender_phone"
                    type="text"
                    class="w-full px-4 py-3 border border-gray-300 rounded-2xl shadow-sm focus:ring-2 focus:ring-gray-900 focus:border-gray-900"
                    placeholder="您的联系电话"
                  >
                </div>
                
                <div class="md:col-span-2">
                  <label class="block text-sm font-medium text-gray-700 mb-2">寄件人地址</label>
                  <textarea 
                    v-model="logisticsForm.sender_address"
                    rows="2"
                    class="w-full px-4 py-3 border border-gray-300 rounded-2xl shadow-sm focus:ring-2 focus:ring-gray-900 focus:border-gray-900 resize-none"
                    placeholder="您的详细地址"
                  ></textarea>
                </div>
                
                <div class="md:col-span-2">
                  <label class="block text-sm font-medium text-gray-700 mb-2">备注</label>
                  <textarea 
                    v-model="logisticsForm.note"
                    rows="2"
                    class="w-full px-4 py-3 border border-gray-300 rounded-2xl shadow-sm focus:ring-2 focus:ring-gray-900 focus:border-gray-900 resize-none"
                    placeholder="其他需要说明的信息"
                  ></textarea>
                </div>
              </div>
              
              <div class="flex justify-end space-x-4">
                <button 
                  type="submit"
                  :disabled="isSubmittingLogistics"
                  class="px-8 py-3 bg-gray-900 text-white rounded-2xl hover:bg-gray-800 transition-colors disabled:opacity-50"
                >
                  {{ isSubmittingLogistics ? '提交中...' : '提交物流信息' }}
                </button>
              </div>
            </form>
          </div>

          <!-- 物流信息显示（已有物流信息时） -->
          <div v-if="request.logistics && request.logistics.length > 0" class="space-y-6">
            <!-- 用户寄回物流信息 -->
            <div v-if="userLogistics.length > 0" class="bg-white rounded-2xl p-8 shadow-sm">
              <div class="flex items-center mb-8">
                <div class="flex-shrink-0">
                  <svg class="h-8 w-8 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                  </svg>
                </div>
                <div class="ml-4">
                  <h2 class="text-2xl font-light text-gray-900">用户寄回物流</h2>
                  <p class="text-gray-600">您寄回商品的物流信息</p>
                </div>
              </div>
              
              <div class="space-y-6">
                <div 
                  v-for="logistic in userLogistics" 
                  :key="logistic.id"
                  class="bg-blue-50 rounded-2xl p-6 border border-blue-200"
                >
                  <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                  <div class="bg-white rounded-2xl p-4 shadow-sm">
                    <div class="flex items-center">
                      <div class="flex-shrink-0">
                        <svg class="h-6 w-6 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
                        </svg>
                      </div>
                      <div class="ml-3">
                        <p class="text-sm font-medium text-gray-500">物流公司</p>
                        <p class="text-lg font-light text-gray-900">{{ logistic.company }}</p>
                      </div>
                    </div>
                  </div>
                  
                  <div class="bg-white rounded-2xl p-4 shadow-sm">
                    <div class="flex items-center">
                      <div class="flex-shrink-0">
                        <svg class="h-6 w-6 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 20l4-16m2 16l4-16M6 9h14M4 15h14" />
                        </svg>
                      </div>
                      <div class="ml-3">
                        <p class="text-sm font-medium text-gray-500">运单号</p>
                        <p class="text-lg font-light text-gray-900 font-mono">{{ logistic.tracking_number }}</p>
                      </div>
                    </div>
                  </div>
                  
                  <div class="bg-white rounded-2xl p-4 shadow-sm">
                    <div class="flex items-center">
                      <div class="flex-shrink-0">
                        <svg class="h-6 w-6 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                        </svg>
                      </div>
                      <div class="ml-3">
                        <p class="text-sm font-medium text-gray-500">发货时间</p>
                        <p class="text-lg font-light text-gray-900">{{ formatDate(logistic.sent_at) }}</p>
                      </div>
                    </div>
                  </div>
                  
                  <div v-if="logistic.expected_delivery_at" class="bg-white rounded-2xl p-4 shadow-sm">
                    <div class="flex items-center">
                      <div class="flex-shrink-0">
                        <svg class="h-6 w-6 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
                        </svg>
                      </div>
                      <div class="ml-3">
                        <p class="text-sm font-medium text-gray-500">预计送达</p>
                        <p class="text-lg font-light text-gray-900">{{ formatDate(logistic.expected_delivery_at) }}</p>
                      </div>
                    </div>
                  </div>
                </div>
                
                <div v-if="logistic.note" class="mt-6">
                  <div class="bg-white rounded-2xl p-4 shadow-sm">
                    <div class="flex items-start">
                      <div class="flex-shrink-0">
                        <svg class="h-6 w-6 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 8h10M7 12h4m1 8l-4-4H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-3l-4 4z" />
                        </svg>
                      </div>
                      <div class="ml-3">
                        <p class="text-sm font-medium text-gray-500 mb-2">备注</p>
                        <p class="text-gray-900">{{ logistic.note }}</p>
                      </div>
                    </div>
                  </div>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 商家寄出物流信息 -->
            <div v-if="adminLogistics.length > 0" class="bg-white rounded-2xl p-8 shadow-sm">
              <div class="flex items-center mb-8">
                <div class="flex-shrink-0">
                  <svg class="h-8 w-8 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
                  </svg>
                </div>
                <div class="ml-4">
                  <h2 class="text-2xl font-light text-gray-900">商家寄出物流</h2>
                  <p class="text-gray-600">商家寄出商品的物流信息</p>
                </div>
              </div>
              
              <div class="space-y-6">
                <div 
                  v-for="logistic in adminLogistics" 
                  :key="logistic.id"
                  class="bg-green-50 rounded-2xl p-6 border border-green-200"
                >
                  <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                    <div class="bg-white rounded-2xl p-4 shadow-sm">
                      <div class="flex items-center">
                        <div class="flex-shrink-0">
                          <svg class="h-6 w-6 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
                          </svg>
                        </div>
                        <div class="ml-3">
                          <p class="text-sm font-medium text-gray-500">物流公司</p>
                          <p class="text-lg font-light text-gray-900">{{ logistic.company }}</p>
                        </div>
                      </div>
                    </div>
                    
                    <div class="bg-white rounded-2xl p-4 shadow-sm">
                      <div class="flex items-center">
                        <div class="flex-shrink-0">
                          <svg class="h-6 w-6 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 20l4-16m2 16l4-16M6 9h14M4 15h14" />
                          </svg>
                        </div>
                        <div class="ml-3">
                          <p class="text-sm font-medium text-gray-500">运单号</p>
                          <p class="text-lg font-light text-gray-900 font-mono">{{ logistic.tracking_number }}</p>
                        </div>
                      </div>
                    </div>
                    
                    <div class="bg-white rounded-2xl p-4 shadow-sm">
                      <div class="flex items-center">
                        <div class="flex-shrink-0">
                          <svg class="h-6 w-6 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                          </svg>
                        </div>
                        <div class="ml-3">
                          <p class="text-sm font-medium text-gray-500">发货时间</p>
                          <p class="text-lg font-light text-gray-900">{{ formatDate(logistic.sent_at) }}</p>
                        </div>
                      </div>
                    </div>
                    
                    <div v-if="logistic.expected_delivery_at" class="bg-white rounded-2xl p-4 shadow-sm">
                      <div class="flex items-center">
                        <div class="flex-shrink-0">
                          <svg class="h-6 w-6 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
                          </svg>
                        </div>
                        <div class="ml-3">
                          <p class="text-sm font-medium text-gray-500">预计送达</p>
                          <p class="text-lg font-light text-gray-900">{{ formatDate(logistic.expected_delivery_at) }}</p>
                        </div>
                      </div>
                    </div>
                  </div>
                  
                  <div v-if="logistic.note" class="mt-6">
                    <div class="bg-white rounded-2xl p-4 shadow-sm">
                      <div class="flex items-start">
                        <div class="flex-shrink-0">
                          <svg class="h-6 w-6 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 8h10M7 12h4m1 8l-4-4H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-3l-4 4z" />
                          </svg>
                        </div>
                        <div class="ml-3">
                          <p class="text-sm font-medium text-gray-500 mb-2">备注</p>
                          <p class="text-gray-900">{{ logistic.note }}</p>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="flex justify-end space-x-4">
            <Link 
              :href="route('after-sales.index')"
              class="px-8 py-3 border border-gray-300 rounded-2xl text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900"
            >
              返回列表
            </Link>
            
            <button 
              v-if="request.can_cancel"
              @click="cancelRequest"
              class="px-8 py-3 border border-red-300 rounded-2xl text-sm font-medium text-red-700 bg-white hover:bg-red-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500"
            >
              取消申请
            </button>
          </div>
        </div>

        <!-- 图片预览模态框 -->
        <div 
          v-if="showImageModal" 
          class="fixed inset-0 bg-black bg-opacity-75 flex items-center justify-center z-50"
          @click="closeImageModal"
        >
          <div class="max-w-4xl max-h-full p-4">
            <img 
              :src="modalImageUrl" 
              alt="凭证图片"
              class="max-w-full max-h-full object-contain rounded-2xl"
              @click.stop
            >
            <button 
              @click="closeImageModal"
              class="absolute top-4 right-4 text-white hover:text-gray-300"
            >
              <svg class="h-8 w-8" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>
        </div>
      </div>
    </div>
  </ShopLayout>
</template>

<script setup>
import { ref, computed } from 'vue'
import { Link, router, useForm } from '@inertiajs/vue3'
import ShopLayout from '@/Layouts/ShopLayout.vue'
import { useNotification } from '@/composables/useNotification'

const { showError, showSuccess } = useNotification()

const props = defineProps({
  request: Object,
  logisticsCompanies: {
    type: Array,
    default: () => []
  }
})

const showImageModal = ref(false)
const modalImageUrl = ref('')

// 物流信息表单
const logisticsForm = useForm({
  company: '',
  tracking_number: '',
  sender_name: '',
  sender_phone: '',
  sender_address: '',
  note: ''
})

const logisticsErrors = ref({})
const isSubmittingLogistics = ref(false)
const isProcessing = ref(false)

// 判断是否显示物流信息填写表单
const shouldShowLogisticsForm = computed(() => {
  // 审核通过且需要物流信息（退货或换货）且还没有物流信息
  if (props.request.status !== 'approved' || 
      (props.request.type !== 'return' && props.request.type !== 'exchange')) {
    return false
  }
  
  // 对于换货申请，如果已经进入处理阶段，不显示物流表单
  if (props.request.type === 'exchange' && props.request.status === 'processing') {
    return false
  }
  
  // 如果已经有物流信息，不显示表单
  if (props.request.logistics && props.request.logistics.length > 0) {
    return false
  }
  
  return true
})

// 分类物流信息
const userLogistics = computed(() => {
  return props.request.logistics?.filter(logistic => logistic.submitted_by === 'user') || []
})

const adminLogistics = computed(() => {
  return props.request.logistics?.filter(logistic => logistic.submitted_by === 'admin') || []
})

const getStatusBadgeClass = (status) => {
  const classes = {
    pending: 'bg-yellow-100 text-yellow-800',
    approved: 'bg-blue-100 text-blue-800',
    rejected: 'bg-red-100 text-red-800',
    processing: 'bg-purple-100 text-purple-800',
    completed: 'bg-green-100 text-green-800',
    cancelled: 'bg-gray-100 text-gray-800'
  }
  return classes[status] || 'bg-gray-100 text-gray-800'
}

const getTypeBadgeClass = (type) => {
  const classes = {
    return: 'bg-purple-100 text-purple-800',
    refund: 'bg-yellow-100 text-yellow-800',
    exchange: 'bg-green-100 text-green-800'
  }
  return classes[type] || 'bg-gray-100 text-gray-800'
}

const getStatusText = (status) => {
  const statusMap = {
    pending: '待处理',
    approved: '已批准',
    rejected: '已拒绝',
    processing: '处理中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return statusMap[status] || status
}

const getTypeText = (type) => {
  const typeMap = {
    return: '退货',
    refund: '退款',
    exchange: '换货'
  }
  return typeMap[type] || type
}

const getOrderStatusText = (status) => {
  const statusMap = {
    pending: '待处理',
    processing: '处理中',
    shipped: '已发货',
    delivered: '已送达',
    cancelled: '已取消'
  }
  return statusMap[status] || status
}

// 获取处理记录动作文本
const getApprovalActionText = (action) => {
  const actionMap = {
    'approve': '审核通过',
    'reject': '审核拒绝',
    'process': '开始处理',
    'complete': '处理完成',
    'cancel': '取消申请',
    'refund': '退款处理',
    'return': '退货处理',
    'exchange': '换货处理'
  }
  return actionMap[action] || action
}


const getImageUrl = (imagePath) => {
  return imagePath.startsWith('http') ? imagePath : `/storage/${imagePath}`
}

const openImageModal = (imagePath) => {
  modalImageUrl.value = getImageUrl(imagePath)
  showImageModal.value = true
}

const closeImageModal = () => {
  showImageModal.value = false
  modalImageUrl.value = ''
}

const cancelRequest = () => {
  if (confirm('确定要取消这个售后申请吗？')) {
    router.post(route('after-sales.cancel', props.request.id), {}, {
      onSuccess: () => {
        router.reload()
      }
    })
  }
}

// 提交物流信息
const submitLogisticsForm = () => {
  // 验证表单
  if (!logisticsForm.company) {
    showError('表单验证失败', '请选择物流公司')
    return
  }
  if (!logisticsForm.tracking_number) {
    showError('表单验证失败', '请填写物流单号')
    return
  }
  
  isSubmittingLogistics.value = true
  logisticsErrors.value = {}
  
  router.post(route('after-sales.logistics.store', props.request.id), logisticsForm, {
    onSuccess: () => {
      isSubmittingLogistics.value = false
      router.reload()
    },
    onError: (errors) => {
      isSubmittingLogistics.value = false
      logisticsErrors.value = errors
      const firstError = Object.values(errors)[0]
      if (firstError) {
        showError('提交失败', Array.isArray(firstError) ? firstError[0] : firstError)
      }
    }
  })
}

const formatDate = (date) => {
  if (!date) return '-'
  const dateObj = new Date(date)
  if (isNaN(dateObj.getTime())) return '-'
  return dateObj.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 换货流程相关方法
const exchangeSteps = ['return_shipped', 'return_received', 'new_sent', 'new_delivered']

// 检查换货步骤是否完成
const isExchangeStepCompleted = (step) => {
  if (!props.request.extended_status) return false
  const currentStepIndex = exchangeSteps.indexOf(props.request.extended_status)
  const stepIndex = exchangeSteps.indexOf(step)
  return currentStepIndex >= stepIndex
}

// 获取换货步骤样式
const getExchangeStepClass = (step) => {
  if (isExchangeStepCompleted(step)) {
    return 'bg-gray-900 text-white'
  } else if (props.request.extended_status === step) {
    return 'bg-gray-700 text-white'
  } else {
    return 'bg-gray-300 text-gray-600'
  }
}

// 获取换货步骤文本样式
const getExchangeStepTextClass = (step) => {
  if (isExchangeStepCompleted(step)) {
    return 'text-gray-900 font-medium'
  } else if (props.request.extended_status === step) {
    return 'text-gray-700 font-medium'
  } else {
    return 'text-gray-500'
  }
}

// 获取换货步骤编号
const getExchangeStepNumber = (step) => {
  return exchangeSteps.indexOf(step) + 1
}

// 检查是否可以确认送达
const canConfirmNewDelivered = computed(() => {
  return props.request.extended_status === 'new_sent' || 
         (props.request.extended_status === 'new_delivered' && !isExchangeStepCompleted('new_delivered'))
})

// 确认新商品已送达
const confirmNewDelivered = () => {
  isProcessing.value = true
  
  router.post(route('after-sales.confirm-delivered', props.request.id), {}, {
    onSuccess: () => {
      isProcessing.value = false
    },
    onError: () => {
      isProcessing.value = false
    }
  })
}

// 检查是否接近超时（使用后端数据）
const isNearTimeout = computed(() => {
  return props.request.is_near_timeout || false
})

// 获取超时提醒消息（使用后端数据）
const getTimeoutMessage = () => {
  return props.request.timeout_message || ''
}

// 获取当前步骤描述
const getCurrentStepDescription = () => {
  if (!props.request.extended_status) return null
  
  const descriptions = {
    'return_shipped': '您已寄回原商品，等待商家确认收货。预计1-2个工作日完成确认。',
    'return_received': '商家已确认收到您寄回的商品，正在准备新商品。预计1-3个工作日寄出。',
    'new_sent': '新商品已寄出，请注意查收。您可以通过物流信息跟踪包裹状态。',
    'new_delivered': '新商品已送达，换货流程即将完成。请确认商品无误。'
  }
  
  return descriptions[props.request.extended_status] || null
}
</script>
